package com.coszero.utils.system

import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager

/**
 * Desc： 软键盘工具类型，打开或关闭软键盘
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2020/6/16 12:03
 * @version 1
 */
object KeyBoardUtils {
    /**
     * 判断软键盘是否已经打开
     *
     * @param context
     * @return
     */
    fun isKeyBoardOpened(context: Context): Boolean {
        val inputMethodManager: InputMethodManager? = context.getApplicationContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        return inputMethodManager != null && inputMethodManager.isActive()
    }

    /**
     * 打卡软键盘
     *
     * @param mEditText 输入框
     * @param mContext 上下文
     */
    fun openKeybord(mEditText: View?, mContext: Context) {
        val imm: InputMethodManager? = mContext
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        if (imm != null) {
            imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN)
            imm.toggleSoftInput(
                InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY
            )
        }
    }

    /**
     * 关闭软键盘
     *
     * @param mEditText 输入框
     * @param mContext 上下文
     */
    fun closeKeybord(mEditText: View, mContext: Context) {
        val imm: InputMethodManager? = mContext
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?

        if (imm != null) {
            imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0)
        }
    }
}